//
// Created by sgyt on 2020/4/26.
// pthread_testcancel 在线程取消状态改变时将会触发

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void *pthread_fun1(void *arg)
{
    //设置线程取消类型为不能取消
    int oldState;
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,&oldState);
    printf("pthread State is %d ，pthread oldState is %d\n",PTHREAD_CANCEL_DISABLE,oldState);

    //等待主线程的pthread_cancel
    sleep(5);
    printf("pthread_testcancel first\n");
    pthread_testcancel();

    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,&oldState);
    printf("pthread State is %d ，pthread oldState is %d\n",PTHREAD_CANCEL_ENABLE,oldState);

    //再次使用取消
    sleep(5);
    printf("pthread_testcancel second\n");
    pthread_testcancel();

}


int main(int argc,char *argv[])
{
    pthread_t p1,p2;

    //创建线程1
    pthread_create(&p1,NULL,pthread_fun1,NULL);

    //等待线程
    sleep(1);

    //线程取消
    pthread_cancel(p1);
    printf("main pthread_cancel is start\n");

    //等待线程
    pthread_join(p1,NULL);
    printf("main process is finish\n");
    return 0;
}